// pages/pyse/pyse.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    orderInfo: {},
    orderGoods:[],
    totalAmount:0,
    loading: false
  },
  loadOrderDetail: function(orderId) {
    var token = wx.getStorageSync('token');
    var that = this;
    this.setData({ loading: true });
    
    wx.request({
      url: 'http://admin.bsmall.byesame.com/wx/order/detail',
      method: 'GET',
      header: {
        'x-byesame-token': token
      },
      data: {
        orderId: orderId
      },
      success: function(res) {
        console.log('pay',res);
        that.setData({ loading: false });
        if (res.statusCode === 200) {
          var orderGoods = res.data.data.orderGoods
          var totalAmount = that.calculateTotalAmount(orderGoods);
          that.setData({
            orderInfo: res.data.data.orderInfo,
            totalAmount: totalAmount,
            orderGoods: orderGoods
          });
        } else {
          wx.showToast({
            title: res.data.msg || '获取订单详情失败',
            icon: 'none'
          });
        }
      },
      fail: function(err) {
        that.setData({ loading: false });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  calculateTotalAmount: function(goodsList) {
    if (!goodsList || goodsList.length === 0) {
      return 0;
    }
    var total = 0;
    for (var i = 0; i < goodsList.length; i++) {
      var goods = goodsList[i];
      var price = parseFloat(goods.price) || 0;
      var number = parseInt(goods.number) || 0;
      total += price * number;
    }
    
    return total.toFixed(2);
  },
  cancelOrderRequest: function(orderId, index) {
    var token = wx.getStorageSync('token');
    var that = this;
    
    wx.showLoading({
      title: '取消中...',
    });
  
    wx.request({
      url: 'http://admin.bsmall.byesame.com/wx/order/cancel',
      method: 'POST',
      header: {
        'x-byesame-token': token,
        'content-type': 'application/json'
      },
      data: {
        orderId: orderId
      },
      success: function(res) {
        wx.hideLoading();
        console.log('取消订单接口返回:', res);
        console.log(orderId);
        if (res.statusCode == 200) {
          wx.showToast({
            title: '取消成功',
            icon: 'success',
            duration: 1500
          });
          
          // 重新加载订单详情
          setTimeout(() => {
            that.loadOrderDetail(orderId);
          }, 1600);
          
        } else {
          wx.showToast({
            title: res.data.msg || '取消失败',
            icon: 'none'
          });
        }
      },
      fail: function(err) {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },
  deleteOrder(e) {
    var orderId = this.data.orderId;
    console.log('从页面数据获取的orderId:', orderId);
    
    var that = this;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个订单吗？',
      confirmColor: '#e4393c',
      success: (res) => {
        if (res.confirm) {
          // 用户点击确定
          this.deleteOrderRequest(orderId);
        }
      }
    });
  },
  deleteOrderRequest: function(orderId) {
    const token = wx.getStorageSync('token');
    
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '删除中...',
    });

    wx.request({
      url: 'http://admin.bsmall.byesame.com/wx/order/delete',
      method: 'POST',
      header: {
        'x-byesame-token': token,
        'content-type': 'application/json'
      },
      data: {
        orderId: orderId
      },
      success: (res) => {
        wx.hideLoading();
        console.log('删除订单接口返回:', res);
        
        if (res.statusCode === 200) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          setTimeout(() => {
            // 获取页面栈
            var pages = getCurrentPages();
            if (pages.length > 1) {
              // 获取上一页实例
              var prevPage = pages[pages.length - 2];
              // 调用上一页的刷新方法
              if (prevPage && typeof prevPage.loadShowList === 'function') {
                prevPage.loadShowList(prevPage.data.activeTab || 0);
              }
            }
            // 返回上一页
            wx.navigateBack();
          }, 1600);
          
        } else {
          wx.showToast({
            title: res.data.msg || '删除失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('删除订单请求失败:', err);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },
  cancelOrder: function(e) {
    // 方法1：从页面数据中获取 orderId
    var orderId = this.data.orderId;
    console.log('从页面数据获取的orderId:', orderId);
    
    var that = this;
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？',
      confirmColor: '#e4393c',
      success: function(res) {
        if (res.confirm) {
          that.cancelOrderRequest(orderId);
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var orderId = options.orderId;
    console.log('接收到的订单ID:', orderId);
    
    this.setData({
      orderId: orderId
    });
    
    // 根据订单ID获取订单详情
    this.loadOrderDetail(orderId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})